package com.bobo.rbac.auth.filter;

import cn.hutool.jwt.JWT;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 * @description:
 * @author: BOBO
 * @time: 2022/7/24 22:31
 */

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
@Autowired
    RedisTemplate redisTemplate;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String requestURI = request.getRequestURI();//获取请求的路径

        if(requestURI.contains("/auth/")){
            //若登录则进入过滤器链
            filterChain.doFilter(request, response);
            return;
        }
        //获取token
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            //放行
            filterChain.doFilter(request, response);
            return;
        }
        //校验合法性
        if(!JWT.of(token).setKey("bobo".getBytes()).validate(0)){
            //放行
            filterChain.doFilter(request, response);
            return;
        }

        //解析token
        String username;
        List<GrantedAuthority> auths;
        try {
            //使用hutool工具类解析token
            JWT jwt = JWT.of(token);
            username= (String) jwt.getPayload("username");

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token非法");
        }
        if(Objects.isNull(username)){
            throw new RuntimeException("用户未登录");
        }

   /*     Collection<? extends GrantedAuthority>  authss =
                (Collection<? extends GrantedAuthority>) redisTemplate.opsForValue().get("login:" + username);
   */
        //从redis获取当前登录人的角色信息
        Collection<? extends GrantedAuthority> authss =
                (Collection<? extends GrantedAuthority>) redisTemplate.opsForValue().get("login:" + username);
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(username,null,authss );
        //把用户相关的信息设置到security 上下文中,让security认为用户是登录状态
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //放行
        filterChain.doFilter(request, response);
    }
}
